package com.tyqx.hashchainbiz;

// import com.alibaba.fastjson.JSON;
import com.tyqx.hashchainbean.module.*;
import com.tyqx.hashchainbean.vo.MerkleRootVO;
import com.tyqx.hashchainbiz.service.NoHashValueJsonService;
import com.tyqx.hashchainutil.common.HashValueUtil;
import hashchainutil.common.EmptyUtils;
import hashchainutil.common.MerkleUtil;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
public class Scheduler {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



    @Resource
    private NoHashValueJsonService noHashValueJsonService;

    @Resource
    private MongoTemplate mongoTemplate;

    ///@Async
    //表示每隔秒
//    @Scheduled(fixedRate = 60 * 1000 * 10)
    @Scheduled(fixedDelay = 1000 * 10)
    public void testTasks() throws Exception {
        CryptoPrimitives suite = new CryptoPrimitives();
        suite.init();
        System.out.println("上链定时任务执行时间：" + dateFormat.format(new Date()));
        Integer status=0;
        List<String> userNameList=noHashValueJsonService.selectUserName(status);
        if(EmptyUtils.isNotEmpty(userNameList)) {
            Random r = new Random();
            int userNameIndex = r.nextInt(userNameList.size());
            String userName = userNameList.get(userNameIndex);
            Integer pageSize = 10000;
            List<NoHashValueJson> noHashValueJsons = noHashValueJsonService.selectBatchGroupByUserName(userName, pageSize);
            List<String> hashValueList = new ArrayList<>();
            List<Long> idList = new ArrayList<>();
            for (int i = 0; i < noHashValueJsons.size(); i++) {
                NoHashValueJson noHashValueJson = noHashValueJsons.get(i);
                String hashValue = noHashValueJson.getHashValue();
                long id = noHashValueJson.getId();
                hashValueList.add(hashValue);
                idList.add(id);
            }

            String rootHashValue=null;
            if(hashValueList.size()>0){
                //rootHashValue = MerkleUtil.getMerkleRoot(hashValueList, suite);
                List<List<String>> merkleTree = MerkleUtil.computeMerkleTree(hashValueList, suite);
                Integer merkleTreeSize=merkleTree.size();
                if(merkleTree.get(merkleTreeSize-1).size()==1){
                    rootHashValue = merkleTree.get(merkleTreeSize-1).get(0);
                }else{
                    throw  new  Exception("computeMerkleTree error");
                }
                HashIndex hashIndex = HashValueUtil.insertHashValue(rootHashValue, userName,mongoTemplate);
                String txId = hashIndex.getTxId();
                Long blockNum = hashIndex.getBlockNum();
                if (EmptyUtils.isNotEmpty(txId) && EmptyUtils.isNotEmpty(blockNum)) {
                    System.out.println("数据库信息上链成功");
                    for (NoHashValueJson noHashValueJson : noHashValueJsons) {
                        noHashValueJson.setRootHashValue(rootHashValue);
                        noHashValueJson.setTxId(txId);
                        noHashValueJson.setBlockNum(blockNum);
                        noHashValueJson.setTxTimeStamp(hashIndex.getTxTimeStamp());
                    }
                    noHashValueJsonService.updateBatchStatus(1, hashIndex, idList);
                    MerkleRootVO merkleRootVO=new MerkleRootVO();
                    //merkleRootVO.setHashValueList(hashValueList);
                    merkleRootVO.setMerkleTree(merkleTree);
                    merkleRootVO.setRootHashValue(rootHashValue);
                    mongoTemplate.insert(merkleRootVO,"merkleRoot");
                    /*boolean flag=mongoTemplate.exists(new Query(),"merkleRoot");
                    if(flag){
                        mongoTemplate.getCollection("merkleRoot").createIndex(Indexes.ascending("rootHashValue"));
                    }*/
                }
            }

        }

        System.out.println("上链定时任务结束时间：" + dateFormat.format(new Date()));
    }
}